package cn.sc.hunter.framework.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * JSON 工具类
 */
public final class JsonUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * POJO 转换为 JSON 字符串
     */
    public static <T> String toJson(T obj) {
        String json;
        try {
            json = OBJECT_MAPPER.writeValueAsString(obj);
        } catch (Exception e) {
            LOGGER.error("POJO 转换为 JSON 字符串失败", e);
            throw new RuntimeException(e);
        }
        return json;
    }

    /**
     * JSON 字符串 转换为 POJO
     */
    public static <T> T fromJson(String json, Class<T> type) {
        T t;
        try {
            t = OBJECT_MAPPER.readValue(json, type);
        } catch (Exception e) {
            LOGGER.error("JSON 字符串 转换为 POJO 失败", e);
            throw new RuntimeException(e);
        }
        return t;
    }
}
